import React, { Component } from 'react'
import Home from './Accountingbook/Home'
import Add from './Accountingbook/Add'
import { Switch, Route, Redirect } from 'react-router-dom'
import './App.css'
import Ctx from './Accountingbook/store/Ctx'

//共同的父组件 状态提升
export default class App extends Component {

  state = {
    accountlist: [ //type=0 支出 =1 收入
      { id: 1, title: '吃喝', total: 20, type: 0, sed: false, bz: '吃饭了' },
      { id: 2, title: '外包', total: 2000, type: 1, sed: true, bz: '写了两个小程序' },
    ]
  }

  //总支出
  changeAll = () => {
    return this.state.accountlist.reduce((p, n) => {
      if (n.type == 0) {
        return p + n.total
      }
      return p
    }, 0)
  }

  //总结余
  changedel = () => {
    return this.state.accountlist.reduce((p, n) => {
      if (n.type == 1) {
        return p + n.total
      }
      return p
    }, 0)
  }

  //修改sed属性 payload=id
  changeSed = (id) => {
    let newlist = [...this.state.accountlist]
    newlist.forEach(item => {
      if (item.id == id) {
        return item.sed = !item.sed
      }
    })
    this.setState({ list: newlist })
  }

  //清除 已选择
  clearSedTrue = () => {
    let newlist = this.state.accountlist.filter(item => {
      return !item.sed
    })
    this.setState({ accountlist: newlist })
  }
  //单个删除
  dellist = (id) => {
    let newlist = this.state.accountlist.filter(item => {
      return item.id !== id
    })
    this.setState({ accountlist: newlist })
  }

  //反选 payload = 布尔值
  changeAllSed = (c) => {
    let newlist = [...this.state.accountlist]
    newlist.forEach(item => {
      item.sed = c
    })
    this.setState({ accountlist: newlist })
  }

  //添加
  addlist=(obj)=>{
    this.setState({accountlist:[...this.state.accountlist,obj]})
  }


  render() {
    return (<Ctx.Provider value={{
      ...this.state,
      changeAll: this.changeAll,
      changedel: this.changedel,
      changeSed: this.changeSed,
      clearSedTrue: this.clearSedTrue,
      dellist: this.dellist,
      changeAllSed: this.changeAllSed,
      addlist:this.addlist
    }}>
      <div className='homebox'>
        <Switch>
          <Route path='/home' component={Home} />
          <Route path='/add' component={Add} />
          <Redirect from='/' to='/home' />
        </Switch>
      </div>
    </Ctx.Provider>

    )
  }
}
